package com.zhentao.service;

import com.alibaba.fastjson.JSON;
import com.zhentao.api.article.schedule.ISchedule;
import com.zhentao.model.dtos.ResponseResult;
import com.zhentao.model.enums.TaskTypeEnum;
import com.zhentao.model.schedule.dto.Task;
import com.zhentao.model.wemedia.pojo.WmNews;
import com.zhentao.utils.common.ProtostuffUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
@Service
@Slf4j
public class WmNewTaskServiceImpl implements WmNewTaskService {
    @Autowired
    private ISchedule iSchedule;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Override
    public void addNewsToTask(Integer id, Date publishTime) {
        log.info("添加任务到延迟服务中----begin");

        Task task = new Task();
        task.setExecuteTime(publishTime.getTime());//文章发布时间  毫秒值
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        byte[] serialize = ProtostuffUtil.serialize(wmNews);
        task.setParameters(serialize);

        iSchedule.addTask(task);
        log.info("添加任务到延迟服务中----end");
    }

    //消费任务 审核文章
    @Scheduled(fixedRate = 1000)//固定频率 每一秒拉取一次
    @Override
    public void scanNewsByTask() {
        log.info("消费任务 审核文章");

        ResponseResult responseResult = iSchedule.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(responseResult.getCode().equals(200) && responseResult.getData() != null){
            //消费任务
            String TaskJson = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(TaskJson, Task.class);
            //反序列化
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);
            wmNewsAutoScanService.autoScanWnMews(wmNews.getId());
        }

    }
}
